<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div class="topbox">
        <el-input
          placeholder="请输入内容"
          v-model="querinfo.query"
          clearable
          @clear="getdatas"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getdatas"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="adddialogvisble = true"
          >添加用户</el-button
        >
      </div>
      <el-table :data="userdata" style="width: 100%">
        <el-table-column type="index" label="##"> </el-table-column>
        <el-table-column prop="username" label="名称"> </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="类型"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userstatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template v-slot="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showuserdata(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removebyid(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-share"
                size="mini"
                @click="setroles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querinfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="querinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totli"
      >
      </el-pagination>
      <el-dialog
        title="添加用户"
        :visible.sync="adddialogvisble"
        width="50%"
        @close="closedialog"
      >
        <el-form
          :model="addfrom"
          :rules="addfromrules"
          ref="addfromref"
          label-width="80px"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addfrom.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addfrom.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addfrom.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="moblie">
            <el-input v-model="addfrom.moblie"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="adddialogvisble = false">取 消</el-button>
          <el-button type="primary" @click="adduserrus()">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="修改用户信息"
        :visible.sync="updatauser"
        width="30%"
        @close="closeupdata"
      >
        <el-form
          :model="updatafrom"
          :rules="updatafromrules"
          ref="updatafrom"
          label-width="80px"
        >
          <el-form-item label="用户名称">
            <el-input :value="updatafrom.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="updatafrom.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="updatafrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updatauser = false">取 消</el-button>
          <el-button type="primary" @click="updatafromyes">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="rolesis" width="50%">
        <div>
          <p>当前的用户：{{ rolesuserinfo.username }}</p>
          <p>当前的角色：{{ rolesuserinfo.role_name }}</p>
          <p>
            分配角色：
            <el-select v-model="newroleid" placeholder="请选择">
              <el-option
                v-for="item in rolesallliist"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rolesis = false">取 消</el-button>
          <el-button type="primary" @click="updatarolesid">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var checkemail = (rule, value, cb) => {
      const emalirule = /^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (emalirule.test(value)) return cb();
      cb(new Error("输入合法邮箱"));
    };
    var checkemobli = (rule, value, cb) => {
      const moblirule =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (moblirule.test(value)) return cb();
      cb(new Error("输入合法手机号"));
    };
    return {
      querinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userdata: [],
      totli: 0,
      adddialogvisble: false,
      updatauser: false,
      addfrom: {
        username: "",
        password: "",
        email: "",
        moblie: "",
      },
      addfromrules: {
        username: [
          { required: true, message: "输入名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "输入密码", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            validator: checkemail,
            trigger: "blur",
          },
        ],
        moblie: [
          { required: true, message: "输入电话", trigger: "blur" },
          {
            validator: checkemobli,
            trigger: "blur",
          },
        ],
      },
      updatafrom: {},
      updatafromrules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            validator: checkemail,
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "输入有效电话", trigger: "blur" },
          {
            validator: checkemobli,
            trigger: "blur",
          },
        ],
      },
      rolesis: false,
      rolesuserinfo: {},
      rolesallliist: {},
      newroleid: "",
    };
  },
  created() {
    this.getdatas();
  },
  methods: {
    async getdatas() {
      const { data: res } = await this.$http.get("users", {
        params: this.querinfo,
      });
      if (res.meta.status !== 200) return this.$message.error("获取用户表失败");
      this.userdata = res.data.users;
      this.totli = res.data.total;
    },
    handleSizeChange(newSize) {
      this.querinfo.pagesize = newSize;
      this.getdatas();
    },
    handleCurrentChange(newcurrent) {
      this.querinfo.pagenum = newcurrent;
      this.getdatas();
    },
    async userstatus(newstatu) {
      const { data: res } = await this.$http.put(
        `users/${newstatu.id}/state/${newstatu.mg_state}`
      );
      if (res.meta.status !== 200) {
        newstatu.mg_state = !newstatu.mg_state;
        return this.$message.error("更新失败");
      }
      this.$message.success("更新成功");
    },
    closedialog() {
      this.$refs.addfromref.resetFields();
    },
    adduserrus() {
      this.$refs.addfromref.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addfrom);
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        this.adddialogvisble = !this.adddialogvisble;
        this.getdatas();
      });
    },
    async showuserdata(id) {
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("查询失败");
      }
      this.$message.success("查询成功");
      this.updatafrom = res.data;
      this.updatauser = !this.updatauser;
    },
    closeupdata() {
      this.$refs.updatafrom.resetFields();
    },
    updatafromyes() {
      this.$refs.updatafrom.validate(async (valid) => {
        if (!valid) return this.$message.error("检查数据合法性");
        const { data: res } = await this.$http.put(
          `users/${this.updatafrom.id}`,
          { email: this.updatafrom.email, mobile: this.updatafrom.mobile }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新失败");
        }
        this.getdatas();
        return this.$message.success("更新成功");
      });
      this.updatauser = !this.updatauser;
    },
    async removebyid(id) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res !== "confirm") return this.$message.success("取消成功");
      if (res == "confirm") {
        const { data: res } = await this.$http.delete(`users/${id}`);
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.getdatas();
        this.$message.success("删除成功");
      }
    },
    async setroles(info) {
      console.log(this.userdata);
      this.rolesis = true;
      this.rolesuserinfo = info;
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesallliist = res.data;
    },
    async updatarolesid() {
      if (!this.newroleid) return this.$message.error("请选择角色");
      const { data: res } = await this.$http.put(
        `users/${this.rolesuserinfo.id}`,
        { rid: this.newroleid }
      );
      if (res.meta.status != 200) return this.$message.error("跟更新角色失败");
      this.getdatas();
      this.$message.success("更新成功");
      this.rolesis = false;
    },
  },
};
</script>

<style  scoped>
.el-breadcrumb {
  font-size: 12px;
}
.box-card {
  margin-top: 20px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.topbox {
  width: 500px;
  display: flex;
  justify-content: space-between;
}
.el-button {
  margin: 0 10px;
}
</style>